//
//  ArriveserviceListViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/4/16.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import CRRefresh
import Alamofire

class ArriveserviceListViewController: BaseViewController {
 
    let arrivceCell = "arrivceCell"
    let arrivceDidCell = "arrivceDidCell"
    var status:Int?
    var arrivcServices:[ArriveServiceModel]?
    
    
    
    @IBOutlet var arriveServiceTableview: UITableView!
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        page = 1
        status = 0
        initSegmentControl()
        requstArriveServiceList(page: page!, status: status!)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        baseSetNavRightButtonWithTitle("添加服务")
        configView()
    }
    
    override func baseNavRightButtonPressed(_ button: UIButton) {
        print("添加服务")
        let arriveVC = ArriveStoreViewController()
        arriveVC.title = "添加服务"; self.navigationController?.pushViewController(arriveVC, animated: true)
    }

    func initSegmentControl() -> Void {
        let btnDataSource = ["未完成","已完成"]
        let yysegment = YJSegmentedControl.init(frame: CGRect(x:0,y:0,width:kScreenWidth,height:44), titleDataSource: btnDataSource, backgroundColor: UIColor.white, titleColor: BaseColor.DarkGrayColor, titleFont: UIFont.systemFont(ofSize: 14), select: BaseColor.NavColor, buttonDownColor: BaseColor.NavColor, delegate: self)
        self.view .addSubview(yysegment!)
    }
    
    func configView() -> Void {
        arriveServiceTableview.delegate = self
        arriveServiceTableview.dataSource = self
        arriveServiceTableview.separatorStyle = .none
        arriveServiceTableview.showsVerticalScrollIndicator = false
        arriveServiceTableview.backgroundColor = BaseColor.BackGroundColor
        arriveServiceTableview.register(UINib(nibName: "ArriveserviceTableViewCell", bundle: nil), forCellReuseIdentifier: arrivceCell)
        arriveServiceTableview.register(UINib(nibName: "ArriveDidTableViewCell", bundle: nil), forCellReuseIdentifier: arrivceDidCell)
        arriveServiceTableview.cr.addHeadRefresh(animator: SlackLoadingAnimator() as CRRefreshProtocol) { [weak self] in
            page = 1
            self?.requstArriveServiceList(page: page!, status: (self?.status!)!)
        }
        arriveServiceTableview.cr.addFootRefresh(animator: SlackLoadingAnimator() as CRRefreshProtocol)  { [weak self] in
            page! += 1
            self?.requstArriveServiceList(page: page!, status: (self?.status!)!)
        }
    }
    
    //网络请求
    //到店服务列表
    func requstArriveServiceList(page:Int,status:Int) -> Void {
        
        Alamofire.request(arriveStoreServiceListUrl, method:.post, parameters: ["page": page,"status":status,"storeid":UserModel.shareUser.data?.storeId ?? String()])
            .responseString { response in
                self.arriveServiceTableview?.cr.endHeaderRefresh()
                self.arriveServiceTableview?.cr.endLoadingMore()
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<BaseArrayData<ArriveServiceModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        if page == 1 {
                            self.arrivcServices?.removeAll()
                            self.arrivcServices = basemodel.data?.data
                        }else {
                            if ((basemodel.data?.data?.count)! > 0) {
                                self.arrivcServices! += (basemodel.data?.data)!
                            }else {
                                return
                            }
                        }
                        print("数据请求成功")
                        self.arriveServiceTableview.reloadData()
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
        
                    }
                    
                case false:
                    print(response.result.error!)
                }
        }
    }
    
    //生成到店服务订单
    func requestProduceArriveOrder(appointId:String,price:String,paytype:String) -> Void {
            let param =
                ["id":appointId,
                 "price":price,
                 "paytype":paytype
            ]
        
        Alamofire.request(finshArriveStoreServiceOrder, method:.post, parameters:param)
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                     
                        page = 1
                        self.requstArriveServiceList(page: page!, status: self.status!)
                        print("成功")
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension ArriveserviceListViewController: YJSegmentedControlDelegate,UITableViewDelegate,UITableViewDataSource {
    
    func segumentSelectionChange(_ selection: Int) {
        status = selection
        page = 1
        requstArriveServiceList(page: page!, status: status!)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.arrivcServices?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        switch status {
        case 0://未完成
            let cell = tableView.dequeueReusableCell(withIdentifier: arrivceCell, for: indexPath) as! ArriveserviceTableViewCell
            cell.selectionStyle = .none
            let model = self.arrivcServices![indexPath.item]
            cell.userNameLabel.text = "姓名：" + model.username
            cell.userPhoneLabel.text = "电话：" + model.phone
            cell.remarksLabel.text = "备注：" + model.description
            if ((model.server) != nil){
                cell.serviceTypeLabel.text = "服务类型：" + (model.server?.name)!
            }
            cell.downOrderLabel.text = "下单时间：" + model.addtime
            cell.carInfoLabel.text = "车牌号：" + model.car
            cell.callBackBlock {//操作订单
                let arriveProducePopview = ArriveProduceView.getArriveProducePopView()
                arriveProducePopview.callBackBlock { (boolValue) in
                    switch boolValue {
                    case true:

                        self.requestProduceArriveOrder(appointId: model.id, price: arriveProducePopview.priceTF.text!, paytype: arriveProducePopview.payway_id)
                        
                        bgWindow?.hidBackgroundWindow()
                    case false:
                        bgWindow?.hidBackgroundWindow()
                    }
                }
                bgWindow = DSHCBcakgroundWindow.setupBackgroundWindowAndShow()
                bgWindow?.shake(toShow: arriveProducePopview)
            }
            
            return cell
        default://已完成
            let cell = tableView.dequeueReusableCell(withIdentifier: arrivceDidCell, for: indexPath) as! ArriveDidTableViewCell
            cell.selectionStyle = .none
            let model = self.arrivcServices![indexPath.item]
            cell.userNameLabel.text = "姓名：" + model.username
            cell.userPhoneLabel.text = "电话：" + model.phone
            cell.remarksLabel.text = "备注：" + model.description
            if ((model.server) != nil){
                cell.serviceTypeLabel.text = "服务类型：" + (model.server?.name)!
            }
            cell.downOrderLabel.text = "下单时间：" + model.addtime
            cell.carInfoLabel.text = "车牌号：" + model.car
            return cell
        }
       
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch status {
        case 0:
            return ScaleHeight(150)
        default:
            return ScaleHeight(120)
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    //    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    //        return 10
    //    }
    
}

